package com.leboncoin.batch;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.leboncoin.bean.SearchItemBean;

/**
 * Compute prices from persisted data
 * @author ben
 */
public class Argus {

	protected static final Logger logger = Logger.getLogger(DaySearch.class.getName());	
	public static void main(String[] args){
		
		EntityManagerFactory emf = null;
		EntityManager em = null;
		EntityTransaction transac = null;
		try {
			emf = Persistence.createEntityManagerFactory("leboncoin");
			em = emf.createEntityManager();
			transac = em.getTransaction();
			transac.begin();
			
			String query = 
					"select s, avg(r.price) "
					+"from SearchItemBean s join s.searchResults r "
					+"group by s";
			
			@SuppressWarnings("unchecked")
			List<Object[]> results = em.createQuery(query).getResultList();
			for (Object[] result:results){
				SearchItemBean searchItemBean = (SearchItemBean) result[0];
				Double average = (Double) result[1];
				searchItemBean.setAverage(Math.round(average));
				em.persist(searchItemBean);
			}
			
			
			transac.commit();
		} catch (Exception e){
			logger.severe(e.getMessage());
			if (e.getCause() != null){
				logger.severe(e.getCause().getMessage());
			}
			if (transac != null && transac.isActive()) transac.rollback();
		} finally {
			if (em != null) em.close();
			if (emf != null) emf.close();
		}
		
	}
}
